<?php

//require 访问控制类
require_once 'AccessControl.php';
require_once 'Validator.php';

class UserController extends Zend_Controller_Action
{

    public function init()
    {
        $this->access = new AccessControl(); //实例化访问控制类
        $this->Validator = new Validator(); //实例化验证类
    }

    public function indexAction()
    {
        
    }

    //查看用户信息
    public function viewAction()
    {
        require_once 'Zend/Session.php';
        $session = new Zend_Session_Namespace('whutoj');
        $userDb = new Application_Model_DbTable_User();
        
        
        //从 Session 中获得 user
        $user = $session->user;
        $uid = $this->getRequest()->getParam('uid');
        
        if(isset($uid))
        {
            //判断 uid 有效性
            $user = $this->Validator->isUidValid($uid);
            
            if($user == false)
            {
                $this->view->ErrorInfo = Validator::UidError;
                return;
            }
            
            $answerDb = new Application_Model_DbTable_Answer();
            $answers = $answerDb->getAnswersByUser($user);
            $userAcceptedAns =0;
            $userAcceptedQues = array();
            
            foreach ($answers as $current)
            {
                if ($current->getMemo() == '$10000001')
                {
                    $userAcceptedAns ++;
                    $userAcceptedQues[] = $current->getQuestion();
                }
            }
            
            $scoreDb = new Application_Model_DbTable_Score();
            $scores = $scoreDb->getScoresByUser($user);
            $score = 0;//用户总得分
            foreach($scores as $curScore)
                $score += $curScore->getTimes() * $curScore->getQuestion()->getScore();

            $this->view->user = $user;
            $this->view->title = $user->getName().' - 用户信息';
            $this->view->score = $score;
            $this->view->userAcceptedAns = $userAcceptedAns;
            $this->view->userAcceptedQues = $userAcceptedQues;
            return;
        }
        
        if(!$this->access->isLogin())
        {
            $this->view->ErrorInfo = Validator::LoginPlz;
            return;
        }
        
        //从 user 中获得当前用户信息
        $uinfoform = new Application_Form_Userinfo();
        $uinfoform->username->setValue($user->getName());
        $uinfoform->email->setValue($user->getEmail());
        $uinfoform->qq->setValue($user->getQq());
        $uinfoform->msn->setValue($user->getMsn());
        
        
        $this->view->uinfo = $uinfoform;
        $this->view->lasttime = $user->getlastTime();
        $this->view->title = '用户信息';
        
       $request = $this->getRequest();
        
        if($request->isPost())
        {
            $post=$request->getPost();
            if($uinfoform->isValid($post))
            {
                //判断是否需要更改密码
                if($post['password'] == '')
                {
                    $user=$this->uinfoNoPw($user,$post);
                    //将更改写入数据库
                    $userDb->updateUser($user);
                    $this->view->ErrorInfo = Validator::UpdateSuccess;
                }
                //判断原密码是否正确
                elseif(md5($post['password']) == $user->getPassword())
                {
                    //验证新密码匹配
                    if($post['newpassword'] == '' || $post['renewpassword'] == '')
                    {
                        $this->view->ErrorInfo = Validator::NewPasswordWrong;
                        return;
                    }
                    if($post['newpassword'] == $post['renewpassword'])
                    {
                        $user=$this->uinfoPw($user,$post);
                        //将更改写入数据库
                        $userDb->updateUser($user);
                        $session->user = $user;
                        $this->view->ErrorInfo = Validator::UpdateSuccess;
                    }
                    else
                    {
                        $this->view->ErrorInfo = Validator::RetypePasswordWrong;
                    }
                }
                else
                {
                    $this->view->ErrorInfo = Validator::PasswordWrong;
                }
            }
        }
        
    }

    //用户列表
    public function listAction()
    {
        $pid = $this->getRequest()->getUserParam('pid');
        $this->view->showpage = true;
        
        $userDb = new Application_Model_DbTable_User();
        $user_count = $userDb->countUsers();//question 总条数
        
        //是否分页
        if($user_count <= Validator::UserListPagesize)
            $this->view->showpage = false;
        else
        {
            if($user_count % Validator::UserListPagesize)
            {
                $pages = (INT)($user_count/Validator::UserListPagesize+1);//有余数的情况
            }
            else
                $pages = $user_count/Validator::UserListPagesize;
            
            $this->view->pages = $pages;
        }
        
        if(isset($pid) && $pid > 1)
        {
            //如果 pid 不合法直接跳转首页
            if($pid <= $pages)
                $users = $userDb->getUsersByRange(Validator::UserListPagesize*($pid-1),Validator::UserListPagesize);
            else
                $this->_redirect('User/list');
        }
        else
        {
            $users = $userDb->getUsersByRange(0,Validator::UserListPagesize);
            $pid = 1;
        }
        
        $this->view->admin = $this->access->isAdmin();
        $this->view->users = $users;
        $this->view->pid = $pid;
    }

    //用户注册
    public function addAction()
    {
        if ($this->access->isLogin())
        {
            $this->view->ErrorInfo = Validator::RegTips;
        }
        
        $form = new Application_Form_FormRegister();
        $this->view->form = $form;
        $request = $this->getRequest();
        if($request->isPost()){
            $post = $request->getPost();
            if($form->isValid($post)){
                if ($post['password'] != $post['repassword']){
                    $this->view->ErrorInfo = Validator::RetypePasswordWrong;
                    return;
                }
            $post = $form->getValues();
                $userdao = new Application_Model_DbTable_User();
                //判断用户信息是否已被注册
                $where = "(ojuName = '".$post['username']."')OR(ojuEmail = '".$post['email']."')";
                $user = $userdao->getUserByWhere($where);
                if($user){
                    if($user->getName() == $post['username'])
                        $this->view->ErrorInfo = Validator::UserExists;
                    else
                        $this->view->ErrorInfo = Validator::EmailExists;
                    return;
                }
                
                $user = new Application_Model_User();
                $mysqldate = date( 'Y-m-d H:i:s',  time());
                $user->setName($post['username'])
                        ->setPassword(md5($post['password']))
                        ->setEmail($post['email'])
                        ->setGender($post['gender'])
                        ->setQq($post['qq'])
                        ->setMsn($post['msn'])
                        ->setImgDefined(FALSE)
                        ->setRegisterTime($mysqldate)
                        ->setLastTime($mysqldate)
                        ->setAdmin(FALSE);
                
                //如果是部署系统后的第一个注册用户,默认为管理员
                if($userdao->countUsers() == 0)
                    $user->setAdmin(TRUE);
                
                $userdao->addUser($user);
                unset($this->view->ErrorInfo);
                $session = new Zend_Session_Namespace('whutoj');
                $session->user = $user;
                $this->_redirect("");
            }
        }
        
    }

    //删除用户
    public function deleteAction()
    {
        //没有登录
        if(!$this->access->isLogin()){
            $this->_redirect('/user/login');
            return;
        }
        
        //类型不匹配    
        $user = $this->access->getSession();
        if(! $user instanceof Application_Model_User){
            $this->access->logout();
           $this->_forward('login');
            return; 
        }
        //从请求的url中来获取被删除的user的id号
        $uid = $this->getRequest()->getUserParam('uid');
        
        //判断 uid 有效性
        if($this->Validator->isUidValid($uid) == false)
        {
            $this->view->ErrorInfo = Validator::UidError;
            return;
        }
            
        
        $userdao = new Application_Model_DbTable_User();
        
        //不是管理员
        if (!$this->access->isAdmin()){
            if($user->getId() == $uid){
                $userdao->deleteUser ($uid); //自杀
                $this->access->logout();
                $this->_redirect("");
            }
            else
                $this->_forward('rights','error');
            return;
        } 
        
        //管理员删除用户
        if($user->getId() == $uid){
            $userdao->deleteUser ($uid); //自杀
            $this->access->logout();
            $this->_redirect("");
        }
        $userdao->deleteUser($uid);
        $this->_forward('list');
        
    }

    //更改用户信息
    public function updateAction()
    {
        $uid = $this->getRequest()->getParam('uid');
        
        //判断 uid 有效性
        $user = $this->Validator->isUidValid($uid);
            
        if($user == false)
        {
            $this->view->ErrorInfo = Validator::UidError;
            return;
        }
        //Todo:独立出 Form
        $uinfoform = new Application_Form_UserUpdate();
        
        $uinfoform->username->setValue($user->getName());
        $uinfoform->email->setValue($user->getEmail());
        $uinfoform->gender->setValue($user->getGender());
        $uinfoform->qq->setValue($user->getQq());
        $uinfoform->msn->setValue($user->getMsn());
        
        $this->view->uinfoform = $uinfoform;
        
        if($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            if($uinfoform->isValid($post))
            {
                //是否修改密码
                if($post['password'] == '')
                    $user=$this->uinfoNoPw($user,$post);
                else
                    $user=$this->uinfoPw($user,$post);
                
                $user->setName($post['username'])
                      ->setGender($post['gender']);
                
                //写入数据库
                $userDb = new Application_Model_DbTable_User();
                $userDb->updateUser($user);
                
                $this->_redirect('User/list');
            }
        }
        
    }
    
    //用户登录
    public function loginAction()
    {
        if ($this->access->isLogin())
        {
            $this->_redirect ('');
            return;
        }
        
        $loginform = new Application_Form_FormLogin();
        $this->view->form = $loginform;
        $request = $this->getRequest();
        if($request->isPost()){
            $post = $request->getPost();
            if ($loginform->isValid($post)){
                $data = $loginform->getValues();
                
                $userdao = new Application_Model_DbTable_User();
                $user = $userdao->getUserByName($data['user'], md5($data['pwd']));
                if ($user == null){
                    $this->view->ErrorInfo = Validator::UserOrPasswordWrong;
                }  else {
                    unset($this->view->ErrorInfo);
                    
                    $mysqldate = date( 'Y-m-d H:i:s',  time());
                    $user->setLastTime($mysqldate);
                    $userdao->updateUser($user);
                    $this->access->login($user);
                    $this->_redirect('index');
                }
            }
        }

    }

    //注销用户
    public function logoutAction()
    {
        $this->access->logout();
    }

    //不修改密码
    public function uinfoNoPw($user, $post)
    {
        $user->setEmail($post['email'])
                ->setQq($post['qq'])
                ->setMsn($post['msn']);
        return $user;
    }

    //修改密码
    public function uinfoPw($user, $post)
    {
        $user->setEmail($post['email'])
                ->setPassword(md5($post['newpassword']))
                ->setQq($post['qq'])
                ->setmsn($post['msn']);
        return $user;
    }

}

